package com.atguigu.gmall.scheduled.jobhandler;

import com.atguigu.gmall.cart.mapper.CartMapper;
import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.scheduled.feign.GmallCartClient;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @description:
 * @author: xie.zh
 * @create: 2021.04.01   09:23
 * @version: 1.0
 */
@Component
public class CartJobHandler {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private GmallCartClient gmallCartClient;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final String KEY_PREFIX = "cart:info:";

    private static final String EXCEPTION_PREFIX = "cart:exception";

    @XxlJob("cartExceptionHandler")
    public ReturnT<String> exceptionHandler(String param) {
        BoundSetOperations<String, String> setOps = this.redisTemplate.boundSetOps(EXCEPTION_PREFIX);
        String userId = setOps.pop();
        while (StringUtils.isNotBlank(userId)) {
            //删除mysql中对应用户的记录
            this.gmallCartClient.deleteCartByUserIdFromMysql(userId);
            //读取redis记录
            BoundHashOperations<String, Object, Object> hashOperations = this.redisTemplate.boundHashOps(KEY_PREFIX + userId);
            List<Object> cartJsons = hashOperations.values();
            //新增到mysql
            if (!CollectionUtils.isEmpty(cartJsons)) {
                cartJsons.forEach(cartJson -> {
                    try {
                        Cart cart = MAPPER.readValue(cartJson.toString(), Cart.class);
                        this.cartMapper.insert(cart);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
            userId = setOps.pop();
        }
        return ReturnT.SUCCESS;
    }
}
